class MoveSiteCrossBorderAssociation < ActiveRecord::Migration
  def self.up
    # move association (merging sites with duplicated names)
    Site.all.each do |s|
      # find the site with minumum id and same name
      homonym = Site.find_all_by_name(s.name, :order => "id").first    
      
      # add the single cross_border of s to homonym  
      homonym.cross_border_ids = homonym.cross_border_ids.push(s.cross_border_id)
      
      unless homonym.id == s.id

        # migrate answeres if there are non in homonym site otherwise, delete it
        s_answers = Answer.find_all_by_site_id(s.id)
        if Answer.find_by_site_id(homonym.id).nil?
          s_answers.each do |a|
            a.site_id = homonym.id
            a.save!
          end
        else
          s_answers.each do |a|
            a.delete
          end
        end
        
        s_role = Role.find_by_coordinated_type_and_coordinated_id("Site", s.id)        
        homonym_role = Role.find_by_coordinated_type_and_coordinated_id("Site", homonym.id)
        
        unless s_role.nil? # nothing to move
          if homonym_role.nil? # there are thing to move, so ensure homonym_role exists
            homonym_role = Role.create!(:users => [], :coordinated => homonym_role)
          end 
          
          s_role.users.each do |u|
            # merge roles of the site to be deleted with roles of the homonym site
            unless homonym_role.users.exists?(u)
              homonym_role.users = homonym_role.users.push(u)
            end
          end
        
          s_role.delete
        end
        
        s.delete
      end
    end
    
    # remove old schema/data
    remove_column :sites, :cross_border_id
  end

  def self.down
    # restore old schema
    add_column :sites, :cross_border_id, :integer
    
    # association data is not restored. sorry.
  end
end
